<template>
  <n-dropdown :options="options" @select="handleSelect">
    <div class="flex cursor-pointer items-center">
      <n-avatar round :size="36" :src="userStore.avatar_url" />
      <div class="ml-12 flex-col flex-shrink-0 items-center">
        <span class="text-14">{{ name }}</span>
        <span class="text-12 opacity-50">[{{ role }}]</span>
      </div>
    </div>
  </n-dropdown>
</template>

<script setup>
import { useUserStore, useAuthStore, usePermissionStore, useRecruiterStore, useSeekerStore } from '@/store'
import { initUserAndPermissions } from '@/router'
import api from '@/api'

const router = useRouter()
const userStore = useUserStore()
const authStore = useAuthStore()
const permissionStore = usePermissionStore()

let name = computed(() => {
  if(userStore.role === 'recruiter') {
    return useRecruiterStore().recruiter.name
  }
  else if(userStore.role === 'seeker') {
    return useSeekerStore().seeker.name
  }
  else if(userStore.role === 'admin') {
    return ''
  }
  else {
    return '未知名称'
  }
})

let role = computed(() => {
  if(userStore.role === 'recruiter') {
    return '招聘者'
  }
  else if(userStore.role === 'seeker') {
    return '求职者'
  }
  else if(userStore.role === 'admin') {
    return '管理员'
  }
  else {
    return '未知角色'
  }
})

const options = reactive([
  {
    label: '个人资料',
    key: 'profile',
    icon: () => h('i', { class: 'i-material-symbols:person-outline text-14' }),
    show: computed(() => permissionStore.accessRoutes?.some((item) => item.path === '/profile')),
  },
  {
    label: '退出登录',
    key: 'logout',
    icon: () => h('i', { class: 'i-mdi:exit-to-app text-14' }),
  },
])

const roleSelectRef = ref(null)
function handleSelect(key) {
  switch (key) {
    case 'profile':
      router.push('/profile')
      break
    case 'toggleRole':
      roleSelectRef.value?.open({
        onOk() {
          initUserAndPermissions().then(() => {
            router.replace('/')
          })
        },
      })
      break
    case 'logout':
      $dialog.confirm({
        title: '提示',
        type: 'info',
        content: '确认退出？',
        async confirm() {
          // try {
          //   await api.logout()
          // } catch (error) {
          //   console.error(error)
          // }
          authStore.logout()
          $message.success('已退出登录')
        },
      })
      break
  }
}
</script>
